package com.yuelife.controller;

import com.yuelife.entity.CUserlikes;
import com.yuelife.service.CCommentService;
import com.yuelife.service.CDiscussionService;
import com.yuelife.service.CUserlikesService;
import com.yuelife.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (CUserlikes)表控制层
 *
 * @author makejava
 * @since 2020-06-18 10:11:58
 */
@RestController
@RequestMapping("cUserlikes")
@CrossOrigin
public class CUserlikesController {
    /**
     * 服务对象
     */
    @Resource
    private CUserlikesService cUserlikesService;

    @Autowired
    private CDiscussionService discussionService;
    @Autowired
    private CCommentService commentService;
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public CUserlikes selectOne(Integer id) {
        return this.cUserlikesService.queryById(id);
    }

    @GetMapping("selectAllUserlike")
    @ResponseBody
    public List<CUserlikes> selecrAllUserlike(Integer userid){
        ResultUtil resultUtil = ResultUtil.success();
        List<CUserlikes> list = cUserlikesService.selectAllUserLiskes(userid);
        Map<String,Object> map = new HashMap();
        map.put("userlikes",list);
        resultUtil.setResult(map);
        return list;
    }
    @GetMapping("/userlike")
    @ResponseBody
    @Transactional
    public ResultUtil userlike(CUserlikes userlikes){
        try {
            if(userlikes.getCommentId()!=0){
                commentService.updateLike(1,userlikes.getCommentId());
            }else {
                discussionService.updateLike(1,userlikes.getDiscussionId());
            }
            cUserlikesService.insert(userlikes);
            return ResultUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.faild();
        }
    }
    @DeleteMapping("/userlike")
    @ResponseBody
    @Transactional
    public ResultUtil deletelike(@RequestBody CUserlikes userlikes){
        System.out.println("用户id"+userlikes.getUserId()+"：帖子id"+userlikes.getDiscussionId());
        try {
            if(userlikes.getCommentId()!=0){
                commentService.updateLike(-1,userlikes.getCommentId());
            }else {
                discussionService.updateLike(-1,userlikes.getDiscussionId());
            }
            boolean flag=cUserlikesService.deleteLike(userlikes);
            return flag==true?ResultUtil.success():ResultUtil.faild();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.faild();
        }
    }

}